<template>
  <div class="history-container">
    <div class="page-header">
      <h2>历史记录</h2>
      <p>查看流程和任务的历史记录</p>
    </div>

    <!-- Tab切换 -->
    <div class="tab-section">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="流程历史" name="process">
          <div class="tab-content">
            <!-- 流程历史筛选 -->
            <div class="filter-section">
              <el-card>
                <el-form :model="processQueryParams" ref="processQueryFormRef" :inline="true">
                  <el-form-item label="流程名称" prop="processName">
                    <el-input
                      v-model="processQueryParams.processName"
                      placeholder="请输入流程名称"
                      clearable
                      style="width: 200px"
                    />
                  </el-form-item>
                  
                  <el-form-item label="流程状态" prop="status">
                    <el-select
                      v-model="processQueryParams.status"
                      placeholder="请选择状态"
                      clearable
                      style="width: 150px"
                    >
                      <el-option label="进行中" value="RUNNING" />
                      <el-option label="已完成" value="COMPLETED" />
                      <el-option label="已暂停" value="SUSPENDED" />
                      <el-option label="已终止" value="TERMINATED" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="发起人" prop="initiator">
                    <el-input
                      v-model="processQueryParams.initiator"
                      placeholder="请输入发起人"
                      clearable
                      style="width: 150px"
                    />
                  </el-form-item>
                  
                  <el-form-item label="发起时间" prop="startTime">
                    <el-date-picker
                      v-model="processQueryParams.startTime"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      style="width: 240px"
                    />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button type="primary" @click="handleProcessQuery">
                      <Icon icon="ant-design:search-outlined" />
                      查询
                    </el-button>
                    <el-button @click="resetProcessQuery">
                      <Icon icon="ant-design:reload-outlined" />
                      重置
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>

            <!-- 流程历史列表 -->
            <div class="list-section">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>流程历史列表</span>
                    <div class="header-actions">
                      <el-button type="primary" @click="exportProcessHistory">
                        <Icon icon="ant-design:download-outlined" />
                        导出
                      </el-button>
                      <el-button @click="refreshProcessList">
                        <Icon icon="ant-design:reload-outlined" />
                        刷新
                      </el-button>
                    </div>
                  </div>
                </template>

                <el-table
                  v-loading="processLoading"
                  :data="processList"
                  style="width: 100%"
                >
                  <el-table-column prop="processName" label="流程名称" min-width="150" />
                  <el-table-column prop="businessKey" label="业务Key" min-width="120" />
                  <el-table-column prop="initiator" label="发起人" width="100" />
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="getStatusType(scope.row.status)">
                        {{ getStatusText(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="startTime" label="发起时间" width="160">
                    <template #default="scope">
                      {{ formatDateTime(scope.row.startTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="endTime" label="结束时间" width="160">
                    <template #default="scope">
                      {{ formatDateTime(scope.row.endTime) || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="duration" label="持续时间" width="120">
                    <template #default="scope">
                      {{ formatDuration(scope.row.duration) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150" fixed="right">
                    <template #default="scope">
                      <el-button
                        type="primary"
                        size="small"
                        @click="handleViewProcessDetail(scope.row)"
                      >
                        详情
                      </el-button>
                      <el-button
                        size="small"
                        @click="handleViewProcessHistory(scope.row)"
                      >
                        记录
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-wrapper">
                  <el-pagination
                    v-model:current-page="processQueryParams.pageNum"
                    v-model:page-size="processQueryParams.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="processTotal"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleProcessSizeChange"
                    @current-change="handleProcessCurrentChange"
                  />
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="任务历史" name="task">
          <div class="tab-content">
            <!-- 任务历史筛选 -->
            <div class="filter-section">
              <el-card>
                <el-form :model="taskQueryParams" ref="taskQueryFormRef" :inline="true">
                  <el-form-item label="任务名称" prop="taskName">
                    <el-input
                      v-model="taskQueryParams.taskName"
                      placeholder="请输入任务名称"
                      clearable
                      style="width: 200px"
                    />
                  </el-form-item>
                  
                  <el-form-item label="流程名称" prop="processName">
                    <el-input
                      v-model="taskQueryParams.processName"
                      placeholder="请输入流程名称"
                      clearable
                      style="width: 200px"
                    />
                  </el-form-item>
                  
                  <el-form-item label="处理人" prop="assignee">
                    <el-input
                      v-model="taskQueryParams.assignee"
                      placeholder="请输入处理人"
                      clearable
                      style="width: 150px"
                    />
                  </el-form-item>
                  
                  <el-form-item label="完成时间" prop="completeTime">
                    <el-date-picker
                      v-model="taskQueryParams.completeTime"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      style="width: 240px"
                    />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button type="primary" @click="handleTaskQuery">
                      <Icon icon="ant-design:search-outlined" />
                      查询
                    </el-button>
                    <el-button @click="resetTaskQuery">
                      <Icon icon="ant-design:reload-outlined" />
                      重置
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>

            <!-- 任务历史列表 -->
            <div class="list-section">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>任务历史列表</span>
                    <div class="header-actions">
                      <el-button type="primary" @click="exportTaskHistory">
                        <Icon icon="ant-design:download-outlined" />
                        导出
                      </el-button>
                      <el-button @click="refreshTaskList">
                        <Icon icon="ant-design:reload-outlined" />
                        刷新
                      </el-button>
                    </div>
                  </div>
                </template>

                <el-table
                  v-loading="taskLoading"
                  :data="taskList"
                  style="width: 100%"
                >
                  <el-table-column prop="taskName" label="任务名称" min-width="150" />
                  <el-table-column prop="processName" label="流程名称" min-width="150" />
                  <el-table-column prop="assignee" label="处理人" width="100" />
                  <el-table-column prop="createTime" label="创建时间" width="160">
                    <template #default="scope">
                      {{ formatDateTime(scope.row.createTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="claimTime" label="认领时间" width="160">
                    <template #default="scope">
                      {{ formatDateTime(scope.row.claimTime) || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="completeTime" label="完成时间" width="160">
                    <template #default="scope">
                      {{ formatDateTime(scope.row.completeTime) || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="duration" label="处理时长" width="120">
                    <template #default="scope">
                      {{ formatDuration(scope.row.duration) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150" fixed="right">
                    <template #default="scope">
                      <el-button
                        type="primary"
                        size="small"
                        @click="handleViewTaskDetail(scope.row)"
                      >
                        详情
                      </el-button>
                      <el-button
                        size="small"
                        @click="handleViewTaskHistory(scope.row)"
                      >
                        记录
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-wrapper">
                  <el-pagination
                    v-model:current-page="taskQueryParams.pageNum"
                    v-model:page-size="taskQueryParams.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="taskTotal"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleTaskSizeChange"
                    @current-change="handleTaskCurrentChange"
                  />
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 流程/任务详情弹窗 -->
    <ProcessDetailModal
      v-model:visible="detailModalVisible"
      :process-data="selectedProcess"
      :task-data="selectedTask"
      :mode="detailMode"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import Icon from '@/components/Icon/Icon.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getProcessHistoryList, 
  getTaskHistoryList, 
  exportHistoryData 
} from '@/api/workflow/process.api'
import ProcessDetailModal from '@/components/Workflow/ProcessDetailModal.vue'

// 引入统一的夜间模式样式
import '@/components/Workflow/styles/dark-theme.css'

// Tab控制
const activeTab = ref('process')

// 流程历史查询参数
const processQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  processName: '',
  status: '',
  initiator: '',
  startTime: []
})

// 任务历史查询参数
const taskQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  taskName: '',
  processName: '',
  assignee: '',
  completeTime: []
})

// 数据
const processLoading = ref(false)
const taskLoading = ref(false)
const processList = ref([])
const taskList = ref([])
const processTotal = ref(0)
const taskTotal = ref(0)

// 弹窗控制
const detailModalVisible = ref(false)
const selectedProcess = ref(null)
const selectedTask = ref(null)
const detailMode = ref('view') // 'view' 模式用于查看流程/任务详情

// 表单引用
const processQueryFormRef = ref()
const taskQueryFormRef = ref()

// Tab切换
const handleTabChange = (tab) => {
  activeTab.value = tab
  if (tab === 'process') {
    loadProcessList()
  } else {
    loadTaskList()
  }
}

// 加载流程历史列表
const loadProcessList = async () => {
  processLoading.value = true
  try {
    const params = {
      pageNum: processQueryParams.pageNum,
      pageSize: processQueryParams.pageSize,
      processName: processQueryParams.processName,
      status: processQueryParams.status,
      initiator: processQueryParams.initiator,
      startTime: processQueryParams.startTime?.[0],
      endTime: processQueryParams.startTime?.[1]
    }
    
    console.log('流程历史查询参数:', params)
    const response = await getProcessHistoryList(params)
    console.log('流程历史API响应:', response)
    
    if (response && response.items) {
      processList.value = response.items || []
      processTotal.value = response.total || 0
      console.log('获取到流程历史数量:', processList.value.length)
    } else if (response && response.data && response.data.items) {
      processList.value = response.data.items || []
      processTotal.value = response.data.total || 0
      console.log('获取到流程历史数量(嵌套格式):', processList.value.length)
    } else {
      console.log('数据格式不符合预期，显示模拟数据')
      ElMessage.info('暂无流程历史数据，显示模拟数据供参考')
      // 使用模拟数据
      processList.value = [
        {
          id: 1,
          processName: '请假申请流程',
          processKey: 'leave_process',
          processInstanceId: 'PI_001',
          businessKey: 'BUSINESS_001',
          initiator: 'admin',
          status: 'COMPLETED',
          startTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
          endTime: new Date(Date.now() - 6 * 24 * 60 * 60 * 1000).toISOString(),
          duration: 86400000
        },
        {
          id: 2,
          processName: '报销申请流程',
          processKey: 'expense_process',
          processInstanceId: 'PI_002',
          businessKey: 'BUSINESS_002',
          initiator: 'admin',
          status: 'COMPLETED',
          startTime: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString(),
          endTime: new Date(Date.now() - 13 * 24 * 60 * 60 * 1000).toISOString(),
          duration: 86400000
        }
      ]
      processTotal.value = processList.value.length
    }
  } catch (error) {
    console.error('加载流程历史失败:', error)
    ElMessage.warning('加载流程历史失败，显示模拟数据供参考。请检查网络连接或联系管理员。')
    // 使用模拟数据
    processList.value = [
      {
        id: 1,
        processName: '请假申请流程',
        processKey: 'leave_process',
        processInstanceId: 'PI_001',
        businessKey: 'BUSINESS_001',
        initiator: 'admin',
        status: 'COMPLETED',
        startTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
        endTime: new Date(Date.now() - 6 * 24 * 60 * 60 * 1000).toISOString(),
        duration: 86400000
      },
      {
        id: 2,
        processName: '报销申请流程',
        processKey: 'expense_process',
        processInstanceId: 'PI_002',
        businessKey: 'BUSINESS_002',
        initiator: 'admin',
        status: 'COMPLETED',
        startTime: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString(),
        endTime: new Date(Date.now() - 13 * 24 * 60 * 60 * 1000).toISOString(),
        duration: 86400000
      }
    ]
    processTotal.value = processList.value.length
  } finally {
    processLoading.value = false
  }
}

// 加载任务历史列表
const loadTaskList = async () => {
  taskLoading.value = true
  try {
    const params = {
      pageNum: taskQueryParams.pageNum,
      pageSize: taskQueryParams.pageSize,
      taskName: taskQueryParams.taskName,
      processName: taskQueryParams.processName,
      assignee: taskQueryParams.assignee,
      completeTime: taskQueryParams.completeTime?.[0],
      endTime: taskQueryParams.completeTime?.[1]
    }
    
    console.log('任务历史查询参数:', params)
    const response = await getTaskHistoryList(params)
    console.log('任务历史API响应:', response)
    
    if (response && response.items) {
      taskList.value = response.items || []
      taskTotal.value = response.total || 0
      console.log('获取到任务历史数量:', taskList.value.length)
    } else if (response && response.data && response.data.items) {
      taskList.value = response.data.items || []
      taskTotal.value = response.data.total || 0
      console.log('获取到任务历史数量(嵌套格式):', taskList.value.length)
    } else {
      console.log('数据格式不符合预期，显示模拟数据')
      ElMessage.info('暂无任务历史数据，显示模拟数据供参考')
      // 使用模拟数据
      taskList.value = [
        {
          id: 1,
          taskName: '审批请假申请',
          processName: '请假流程',
          processInstanceId: 'PI_001',
          assignee: 'admin',
          status: 'COMPLETED',
          createTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
          completeTime: new Date(Date.now() - 6 * 24 * 60 * 60 * 1000).toISOString(),
          duration: 86400000
        },
        {
          id: 2,
          taskName: '审核报销单',
          processName: '报销流程',
          processInstanceId: 'PI_002',
          assignee: 'admin',
          status: 'COMPLETED',
          createTime: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString(),
          completeTime: new Date(Date.now() - 13 * 24 * 60 * 60 * 1000).toISOString(),
          duration: 86400000
        }
      ]
      taskTotal.value = taskList.value.length
    }
  } catch (error) {
    console.error('加载任务历史失败:', error)
    ElMessage.warning('加载任务历史失败，显示模拟数据供参考。请检查网络连接或联系管理员。')
    // 使用模拟数据
    taskList.value = [
      {
        id: 1,
        taskName: '审批请假申请',
        processName: '请假流程',
        processInstanceId: 'PI_001',
        assignee: 'admin',
        status: 'COMPLETED',
        createTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
        completeTime: new Date(Date.now() - 6 * 24 * 60 * 60 * 1000).toISOString(),
        duration: 86400000
      },
      {
        id: 2,
        taskName: '审核报销单',
        processName: '报销流程',
        processInstanceId: 'PI_002',
        assignee: 'admin',
        status: 'COMPLETED',
        createTime: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString(),
        completeTime: new Date(Date.now() - 13 * 24 * 60 * 60 * 1000).toISOString(),
        duration: 86400000
      }
    ]
    taskTotal.value = taskList.value.length
  } finally {
    taskLoading.value = false
  }
}

// 流程历史查询
const handleProcessQuery = () => {
  processQueryParams.pageNum = 1
  loadProcessList()
}

// 重置流程查询
const resetProcessQuery = () => {
  processQueryFormRef.value?.resetFields()
  processQueryParams.pageNum = 1
  loadProcessList()
}

// 刷新流程列表
const refreshProcessList = () => {
  loadProcessList()
}

// 任务历史查询
const handleTaskQuery = () => {
  taskQueryParams.pageNum = 1
  loadTaskList()
}

// 重置任务查询
const resetTaskQuery = () => {
  taskQueryFormRef.value?.resetFields()
  taskQueryParams.pageNum = 1
  loadTaskList()
}

// 刷新任务列表
const refreshTaskList = () => {
  loadTaskList()
}

// 流程分页处理
const handleProcessSizeChange = (size) => {
  processQueryParams.pageSize = size
  loadProcessList()
}

const handleProcessCurrentChange = (page) => {
  processQueryParams.pageNum = page
  loadProcessList()
}

// 任务分页处理
const handleTaskSizeChange = (size) => {
  taskQueryParams.pageSize = size
  loadTaskList()
}

const handleTaskCurrentChange = (page) => {
  taskQueryParams.pageNum = page
  loadTaskList()
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'RUNNING': 'primary',
    'COMPLETED': 'success',
    'SUSPENDED': 'warning',
    'TERMINATED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'RUNNING': '进行中',
    'COMPLETED': '已完成',
    'SUSPENDED': '已暂停',
    'TERMINATED': '已终止'
  }
  return textMap[status] || status
}

// 格式化日期时间
const formatDateTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

// 格式化持续时间
const formatDuration = (duration) => {
  if (!duration) return '-'
  const hours = Math.floor(duration / 3600000)
  const minutes = Math.floor((duration % 3600000) / 60000)
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  }
  return `${minutes}分钟`
}

// 查看流程详情
const handleViewProcessDetail = (process) => {
  selectedProcess.value = process
  detailMode.value = 'view'
  detailModalVisible.value = true
}

// 查看流程历史
const handleViewProcessHistory = (process) => {
  selectedProcess.value = process
  detailMode.value = 'view'
  detailModalVisible.value = true
}

// 查看任务详情
const handleViewTaskDetail = (task) => {
  selectedTask.value = task
  detailMode.value = 'view'
  detailModalVisible.value = true
}

// 查看任务历史
const handleViewTaskHistory = (task) => {
  selectedTask.value = task
  detailMode.value = 'view'
  detailModalVisible.value = true
}

// 导出流程历史
const exportProcessHistory = async () => {
  try {
    const params = {
      type: 'process',
      ...processQueryParams,
      startTime: processQueryParams.startTime?.[0],
      endTime: processQueryParams.startTime?.[1]
    }
    delete params.startTime
    
    const res = await exportHistoryData(params)
    // 处理文件下载
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '流程历史记录.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 导出任务历史
const exportTaskHistory = async () => {
  try {
    const params = {
      type: 'task',
      ...taskQueryParams,
      startTime: taskQueryParams.completeTime?.[0],
      endTime: taskQueryParams.completeTime?.[1]
    }
    delete params.completeTime
    
    const res = await exportHistoryData(params)
    // 处理文件下载
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '任务历史记录.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

onMounted(() => {
  loadProcessList()
})
</script>

<style scoped>
.history-container {
  padding: 24px;
  background: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.tab-section {
  margin-bottom: 24px;
}

.tab-content {
  padding-top: 24px;
}

.filter-section {
  margin-bottom: 24px;
}

.list-section {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 